package com.mdd.common.util.aliyunOss;

import com.aliyun.oss.OSS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class OssUtil {

    @Resource
    private OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.endpoint}") // 新增 endpoint 配置
    private String endpoint;

    @Value("${aliyun.oss.url-expire-time}")
    private Long expireTime;

    /**
     * 上传文件
     * @param file 文件对象
     * @param path 存储路径（如 "images/"）
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file, String path) {
        try {
            // 生成唯一文件名
            String fileName = path + UUID.randomUUID() + "." +
                    StringUtils.getFilenameExtension(file.getOriginalFilename());

            ossClient.putObject(bucketName, fileName,
                    new ByteArrayInputStream(file.getBytes()));

            // 生成访问URL
//            return generateUrl(fileName);
            return generateUrlByEndpoint(fileName);
        } catch (IOException e) {
            log.error("文件上传失败：", e);
            throw new RuntimeException("文件上传失败");
        }
    }

    /**
     * 生成文件访问URL
     */
    private String generateUrl(String fileName) {
        Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);
//        return ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
        return ossClient.generatePresignedUrl(bucketName, fileName, null).toString();
    }

    private String generateUrlByEndpoint(String fileName) {
        // 构造公共访问 URL
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }

//    /**
//     * 删除文件
//     */
//    public void deleteFile(String fileUrl) {
//        String fileName = extractFileName(fileUrl);
//        ossClient.deleteObject(bucketName, fileName);
//    }

}

